package com.atguigu.gmall.order.controller;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CartFeignClient cartFeignClient;

    @Resource
    private OrderService orderService;

    //查询商品清单
    //生成交易号
    @GetMapping("/trade")
    public Map<String,Object> trade(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //生成交易号
        String userId = AuthContextHolder.getUserId(request);
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        String cacheKey = RedisConst.TRADENOKEY_PREFIX + userId;
        redisTemplate.opsForValue().set(cacheKey,tradeNo);
        map.put("tradeNo",tradeNo);
        //查询商品清单
        List<CartInfo> cartInfoList = cartFeignClient.cartListIsChecked();
        List<OrderDetail> orderDetailList = cartInfoList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            return orderDetail;
        }).collect(Collectors.toList());
        map.put("detailArrayList",orderDetailList);
        //总件数totalNum
        Long totalNum = orderDetailList.stream().collect(Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
        map.put("totalNum",totalNum);
        //总金额totalAmount
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderDetail orderDetail : orderDetailList) {
            totalAmount = totalAmount.add(orderDetail.getOrderPrice().multiply(new BigDecimal(orderDetail.getSkuNum())));
        }
        map.put("totalAmount",totalAmount);
        return map;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,
                              String tradeNo,
                              HttpServletRequest request){
        //订单号幂等性校验
        String userId = AuthContextHolder.getUserId(request);
        String cacheKey = RedisConst.TRADENOKEY_PREFIX + userId;
        String o = (String) redisTemplate.opsForValue().get(cacheKey);
        if (!tradeNo.equals(o)){
            return  Result.fail().message("发生了一个未知的错误");
        }
        redisTemplate.delete(cacheKey);
        //校验库存是否充足
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            Long skuId = orderDetail.getSkuId();
            Integer skuNum = orderDetail.getSkuNum();
            Boolean flag = orderService.hasStock(skuId,skuNum);
            if (flag){
                return Result.fail().message("商品库存不足");
            }
        }
        //保存订单
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderService.submitOrder(orderInfo);
        return Result.ok(orderId);
    }

    //根据Id查询订单
    @GetMapping("/getOrderInfo/{orderId}")
    public Result getOrderInfo(@PathVariable Long orderId){
        OrderInfo orderInfo = orderService.getOrderInfo(orderId);
        return Result.ok(orderInfo);
    }

    //拆单 仓库发出的http请求
    @PostMapping("/orderSplit")
    public String orderSplit(Long orderId,String wareSkuMap){
        // 拆单：获取到的子订单集合
        List<OrderInfo> subOrderInfoList = orderService.orderSplit(orderId,wareSkuMap);
        // 封装生成子订单集合
        List<Map> mapList = subOrderInfoList.stream()
                .map(orderInfo -> orderService.initWareOrder(orderInfo)).collect(Collectors.toList());
        return JSONObject.toJSONString(mapList);
    }
}
